package com.alan.netty.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * @author weiBin
 * @date 2018/11/23
 */
public class ByteBufAccess {
    public static void main(String[] args) {
        ByteBuf byteBuf = Unpooled.copiedBuffer("I love you so much", CharsetUtil.UTF_8);
        ByteBufCreate.printByteBuf(byteBuf);
//      set / get
        byteBuf.setByte(2, (byte) 'h');
        System.out.println((char) byteBuf.getByte(2));
        ByteBufCreate.printByteBuf(byteBuf);
//      read / write
        System.out.println((char) byteBuf.readByte());
        byteBuf.writeByte((byte) 'h');
        ByteBufCreate.printByteBuf(byteBuf);
//      slice
        ByteBuf slice = byteBuf.slice(2, 3);
        slice.setByte(0, (byte) 'w');
        System.out.println((char) byteBuf.getByte(2));
        ByteBufCreate.printByteBuf(slice);
        ByteBufCreate.printByteBuf(byteBuf);
//      duplicate
        ByteBuf duplicate = byteBuf.duplicate();
        duplicate.setByte(3, (byte) 'K');
        System.out.println((char) byteBuf.getByte(3));
        ByteBufCreate.printByteBuf(duplicate);
        ByteBufCreate.printByteBuf(byteBuf);
//      Composite
        CompositeByteBuf messageBuf = Unpooled.compositeBuffer(1024);
        messageBuf.addComponent(byteBuf);
        messageBuf.addComponent(slice);
        for (ByteBuf buf : messageBuf) {
            System.out.println(buf.toString());
        }
        messageBuf.removeComponent(1);
        for (ByteBuf buf : messageBuf) {
            System.out.println(buf.toString());
        }
//      headBuf
        ByteBuf headBuf = Unpooled.buffer(10);
        if (headBuf.hasArray()) {
            int i = 0;
            while (headBuf.writableBytes() > 0) {
                headBuf.writeByte(i++);
            }
            int length = headBuf.readableBytes();
            byte[] bytes = new byte[length];
            headBuf.readBytes(bytes);
            int offset = headBuf.arrayOffset();
            handleArray(bytes, offset, length);
        }
        ByteBufCreate.printByteBuf(headBuf);

//      directBuffer
        ByteBuf directBuf = Unpooled.directBuffer(10);
        if (!directBuf.hasArray()) {
            int i = 0;
            while (directBuf.writableBytes() > 0) {
                directBuf.writeByte(i++);
            }
            int length = directBuf.readableBytes();
            byte[] bytes = new byte[length];
            directBuf.getBytes(directBuf.readerIndex(), bytes);
            handleArray(bytes, 0, length);
        }
        ByteBufCreate.printByteBuf(directBuf);
    }

    private static void handleArray(byte[] array, int offset, int len) {
        for (int i = 0; i < len; i++) {
            System.out.println(array[offset + i]);
        }
    }
}
